package com.ympc.controller;

import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.TeacherService;
import com.ympc.service.UsersService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 管理员控制器
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    
    @Resource
    private TeacherService teacherService;
    
    @Resource
    private UsersService usersService;
    
    /**
     * 管理员主页
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index(HttpSession session) {
        Users user = (Users) session.getAttribute("user");
        if (user == null || !"admin".equals(user.getRole())) {
            return "redirect:/";
        }
        return "admin";
    }
    
    /**
     * 教师列表页面
     */
    @RequestMapping(value = "/teachers", method = RequestMethod.GET)
    public String teacherList(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null || !"admin".equals(user.getRole())) {
            return "redirect:/";
        }
        
        List<Teacher> teachers = teacherService.getAllTeachers();
        model.addAttribute("teachers", teachers);
        return "admin/teacherList";
    }
    
    /**
     * 添加教师页面
     */
    @RequestMapping(value = "/teacher/add", method = RequestMethod.GET)
    public String addTeacherPage(HttpSession session) {
        Users user = (Users) session.getAttribute("user");
        if (user == null || !"admin".equals(user.getRole())) {
            return "redirect:/";
        }
        return "admin/addTeacher";
    }
    
    /**
     * 添加教师
     */
    @RequestMapping(value = "/teacher/add", method = RequestMethod.POST)
    public String addTeacher(@RequestParam String username,
                            @RequestParam String password,
                            @RequestParam String realName,
                            @RequestParam(required = false) String gender,
                            @RequestParam(required = false) String college,
                            @RequestParam(required = false) String phone,
                            @RequestParam(required = false) String email,
                            @RequestParam(required = false) String major,
                            @RequestParam(required = false) String subject,
                            @RequestParam(required = false) String jobDescription,
                            HttpSession session,
                            Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null || !"admin".equals(user.getRole())) {
            return "redirect:/";
        }
        
        try {
            // 验证必填字段
            if (username == null || username.trim().isEmpty()) {
                model.addAttribute("error", "用户名不能为空");
                return "admin/addTeacher";
            }
            if (password == null || password.trim().isEmpty()) {
                model.addAttribute("error", "密码不能为空");
                return "admin/addTeacher";
            }
            if (realName == null || realName.trim().isEmpty()) {
                model.addAttribute("error", "真实姓名不能为空");
                return "admin/addTeacher";
            }
            
            // 检查用户名是否已存在
            Users existingUser = usersService.getUserByUsername(username);
            if (existingUser != null) {
                model.addAttribute("error", "用户名已存在");
                return "admin/addTeacher";
            }
            
            // 1. 创建用户账号
            Users newUser = usersService.createUser(username, password, realName, "teacher");
            if (newUser == null || newUser.getId() == null) {
                model.addAttribute("error", "创建用户账号失败");
                return "admin/addTeacher";
            }
            
            // 2. 创建教师信息
            Teacher teacher = new Teacher();
            teacher.setUserId(newUser.getId());
            teacher.setRealName(realName);
            teacher.setGender(gender);
            teacher.setCollege(college);
            teacher.setPhone(phone);
            teacher.setEmail(email);
            teacher.setMajor(major);
            teacher.setSubject(subject);
            teacher.setJobDescription(jobDescription);
            
            boolean success = teacherService.createTeacherInfo(teacher);
            if (success) {
                model.addAttribute("message", "教师添加成功！登录账号已创建：用户名=" + username + "，密码=" + password);
                return "redirect:/admin/teachers";
            } else {
                model.addAttribute("error", "教师添加失败");
                return "admin/addTeacher";
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "添加教师时出错：" + e.getMessage());
            return "admin/addTeacher";
        }
    }
    
    /**
     * 删除教师
     */
    @RequestMapping(value = "/teacher/delete", method = RequestMethod.GET)
    public String deleteTeacher(@RequestParam Integer id, HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null || !"admin".equals(user.getRole())) {
            return "redirect:/";
        }
        
        // 注意：由于外键约束，删除教师会自动删除关联的用户账号
        Teacher teacher = teacherService.getTeacherById(id);
        if (teacher != null) {
            // 删除教师（级联删除用户）
            // 这里需要实现删除方法，暂时先提示
            model.addAttribute("error", "删除功能需要实现TeacherMapper.deleteTeacher方法");
        } else {
            model.addAttribute("error", "教师不存在");
        }
        return "redirect:/admin/teachers";
    }
}

